﻿<script lang="ts" setup name="transferOrder">
import { ref, reactive, onMounted } from "vue";
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from "element-plus";
import { downloadStreamFile } from "/@/utils/download";
import { useTransferOrderApi } from '/@/api/main/transferOrder';
import editDialog from '/@/views/main/transferOrder/component/editDialog.vue'
import viewDialog from '/@/views/main/transferOrder/component/viewDialog.vue'
import remarkDialog from '/@/views/main/transferOrder/component/remarkDialog.vue'
import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from "/@/components/table/importData.vue";
import { useProductApi } from '/@/api/main/product';
import { useCustomerApi } from '/@/api/main/customer';
import transferDislog from '/@/views/main/productCard/component/transferDislog.vue'

const transferOrderApi = useTransferOrderApi();
const printDialogRef = ref();
const editDialogRef = ref();
const viewDialogRef = ref();
const remarkDialogRef = ref();
const importDataRef = ref();
const transferDislogRef = ref();
const state = reactive({
  queryLoading: false,
  exportLoading: false,
  tableLoading: false,
  stores: {},
  showAdvanceQueryUI: true,
  dropdownData: {} as any,
  selectData: [] as any[],
  tableQueryParams: {} as any,
  tableParams: {
    page: 1,
    pageSize: 20,
    total: 0,
    field: 'createTime', // 默认的排序字段
    order: 'descending', // 排序方向
    descStr: 'descending', // 降序排序的关键字符
  },
  tableData: [],
});

// 页面加载时
onMounted(async () => {
  state.queryLoading = true;
  var res = await useProductApi().getSelectList(null, false);
  state.dropdownData.productData = res.data.result;
  var res = await useCustomerApi().getSelectList(null, false);
  state.dropdownData.customerData = res.data.result;
  state.queryLoading = false;
});

// 查询操作
const handleQuery = async (params: any = {}) => {
  state.tableLoading = true;
  state.tableParams = Object.assign(state.tableParams, params);
  const result = await transferOrderApi.page(Object.assign(state.tableQueryParams, state.tableParams)).then(res => res.data.result);
  state.tableParams.total = result?.total;
  state.tableData = result?.items ?? [];
  await getSummary();
  state.tableLoading = false;
};

// 列排序
const sortChange = async (column: any) => {
  state.tableParams.field = column.prop;
  state.tableParams.order = column.order;
  await handleQuery();
};

// 批量删除
const batchDelTransferOrder = () => {
  ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await transferOrderApi.batchDelete(state.selectData.map(u => ({ id: u.id }))).then(res => {
      ElMessage.success(`成功批量删除${res.data.result}条记录`);
      handleQuery();
    });
  }).catch(() => { });
};

// 查询汇总行
const summaryData = ref<any>(null);
const getSummaries = (param: any) => {
  if (!summaryData.value) {
    return [];
  }
  const { columns } = param;
  const sums: any = []; 
  columns.forEach((column: any, index: any) => {
    sums[index] = summaryData.value[column.property];
  })
  return sums;
};

const getSummary = async () => {
  state.tableLoading = true;
  state.tableParams = Object.assign(state.tableParams, {});
  const result = await transferOrderApi.getSummary(Object.assign(state.tableQueryParams, state.tableParams)).then(res => res.data.result);
  state.tableLoading = false;
  summaryData.value = result;
}

handleQuery();
</script>
<template>
  <div class="transferOrder-container" v-loading="state.exportLoading">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
      <el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="销售单号">
              <el-input v-model="state.tableQueryParams.code" clearable placeholder="请输入销售单号" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="发货仓库">
              <el-select v-model="state.tableQueryParams.fromCustomerId" placeholder="请选择发货仓库" clearable>
                <el-option v-for="item in state.dropdownData.customerData" :key="item.id" :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="目标客户">
              <!-- <el-input v-model="state.tableQueryParams.toCustomerId" clearable placeholder="请输入目标客户Id" /> -->
              <el-select v-model="state.tableQueryParams.toCustomerId" placeholder="请选择目标客户" clearable>
                <el-option v-for="item in state.dropdownData.customerData" :key="item.id" :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="产品">
              <el-select v-model="state.tableQueryParams.productId" placeholder="请选择产品" clearable>
                <el-option v-for="item in state.dropdownData.productData" :key="item.id" :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item>
              <el-button-group style="display: flex; align-items: center;">
                <el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'transferOrder:page'"
                  v-reclick="1000"> 查询 </el-button>
                <el-button icon="ele-Refresh" @click="() => state.tableQueryParams = {}"> 重置 </el-button>
                <el-button icon="ele-ZoomIn" @click="() => state.showAdvanceQueryUI = true"
                  v-if="!state.showAdvanceQueryUI" style="margin-left:5px;"> 高级查询 </el-button>
                <el-button icon="ele-ZoomOut" @click="() => state.showAdvanceQueryUI = false"
                  v-if="state.showAdvanceQueryUI" style="margin-left:5px;"> 隐藏 </el-button>
                <el-button type="danger" style="margin-left:5px;" icon="ele-Delete" @click="batchDelTransferOrder"
                  :disabled="state.selectData.length == 0" v-auth="'transferOrder:batchDelete'"> 删除 </el-button>
                <el-button type="warning" style="margin-left:5px;" icon="ele-MostlyCloudy"
                  @click="transferDislogRef.openDialog(null, '调拨库存')" v-auth="'transferOrder:add'"> 调拨库存 </el-button>
                <!-- <el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportTransferOrderCommand">
                  <el-button type="primary" style="margin-left:5px;" icon="ele-FolderOpened" v-reclick="20000"
                    v-auth="'transferOrder:export'"> 导出 </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="select"
                        :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
                      <el-dropdown-item command="current">导出本页</el-dropdown-item>
                      <el-dropdown-item command="all">导出全部</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
</el-dropdown> -->
                <!-- <el-button type="warning" style="margin-left:5px;" icon="ele-MostlyCloudy"
                  @click="importDataRef.openDialog()" v-auth="'transferOrder:import'"> 导入 </el-button> -->
              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="state.tableData" @selection-change="(val: any[]) => { state.selectData = val; }"
        style="width: 100%" v-loading="state.tableLoading" tooltip-effect="light" row-key="id" @sort-change="sortChange"
        border show-summary sum-text="" :summary-method="getSummaries">
        <el-table-column type="selection" width="40" align="center"
          v-if="auth('transferOrder:batchDelete') || auth('transferOrder:export')" />
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop='code' label='销售单号' width="180" show-overflow-tooltip />
        <el-table-column prop='productLabel' label='产品' width="200" show-overflow-tooltip />
        <el-table-column prop='qty' label='数量' width="100" show-overflow-tooltip />
        <el-table-column prop='fromCustomerLabel' label='发货仓库' width="150" show-overflow-tooltip />
        <el-table-column prop='toCustomerLabel' label='目标客户' width="150" show-overflow-tooltip />
        <el-table-column prop='createTime' label='销售时间' width="150" show-overflow-tooltip />
        <el-table-column prop='remark' label='备注' show-overflow-tooltip />
        <el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <ModifyRecord :data="scope.row" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip
          v-if="auth('transferOrder:update') || auth('transferOrder:delete')">
          <template #default="scope">
            <el-button icon="ele-Edit" size="small" text type="primary"
              @click="viewDialogRef.openDialog(scope.row, '查看销售库存')"> 查看
            </el-button>
            <el-button icon="ele-Edit" size="small" text type="primary" @click="remarkDialogRef.openDialog(scope.row)">
              备注
            </el-button>
            <!-- <el-button icon="ele-Edit" size="small" text type="primary"
              @click="transferDislogRef.openDialog(scope.row, '编辑库存调拨')" v-auth="'transferOrder:update'"> 编辑
            </el-button>
            <el-button icon="ele-Delete" size="small" text type="primary" @click="delTransferOrder(scope.row)"
              v-auth="'transferOrder:delete'"> 删除 </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:currentPage="state.tableParams.page" v-model:page-size="state.tableParams.pageSize"
        @size-change="(val: any) => handleQuery({ pageSize: val })"
        @current-change="(val: any) => handleQuery({ page: val })" layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100, 200, 500]" :total="state.tableParams.total" size="small" background />
      <ImportData ref="importDataRef" :import="transferOrderApi.importData"
        :download="transferOrderApi.downloadTemplate" v-auth="'transferOrder:import'" @refresh="handleQuery" />
      <printDialog ref="printDialogRef" :title="'打印库存销售'" @reloadTable="handleQuery" />
      <editDialog ref="editDialogRef" @reloadTable="handleQuery" />
      <transferDislog ref="transferDislogRef" @reloadTable="handleQuery" />
      <viewDialog ref="viewDialogRef" @reloadTable="handleQuery" />
      <remarkDialog ref="remarkDialogRef" @reloadTable="handleQuery" />
    </el-card>
  </div>
</template>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
  width: 100%;
}
</style>
